import React from "react";
import { Table, Button, message, Modal, Input } from "antd";
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { getArticles, deleteArticle } from "../../../api/articles";

interface Article {
  id: string;
  title: string;
  category: string;
  tags: string;
  content: string;
  create_time: string;
}

const BlogArticles: React.FC = () => {
  const [confirmLoading, setConfirmLoading] = React.useState(false);
  const [dataSource, setDataSource] = React.useState<Article[]>([]);
  const [searchText, setSearchText] = React.useState("");
  const [currentPage, setCurrentPage] = React.useState(1); // 当前页码
  const [pageSize, setPageSize] = React.useState(10); // 每页显示数量
  const [total, setTotal] = React.useState(0); // 总数据量

  const handleSearch = async (page: number = currentPage) => {
    // 支持传入页码，默认使用当前页
    try {
      const res = await getArticles(1, 10, searchText);
      setDataSource(res.data);
    } catch (error) {
      message.error("搜索失败");
    }
  };
  const navigate = useNavigate();

  const columns = [
    { title: "ID", dataIndex: "id", width: 80 },
    { title: "标题", dataIndex: "title", width: 180 },
    { title: "分类", dataIndex: "category", width: 100 },
    { title: "标签", dataIndex: "tags", width: 120 },
    { title: "内容", dataIndex: "content" },
    { title: "创建时间", dataIndex: "create_time", width: 240 },
    {
      title: "操作",
      dataIndex: "action",
      width: 100,
      render: (_: any, record: Article) => (
        <div>
          <Button
            type="link"
            onClick={() => navigate(`/blog/articles/edit/${record.id}`)}
            style={{ marginRight: 8 }}
          >
            编辑
          </Button>
          <Button type="link" danger onClick={() => handleDelete(record.id)}>
            删除
          </Button>
        </div>
      ),
    },
  ];

  const handleDelete = async (id: string) => {
    Modal.confirm({
      title: "确认删除",
      content: "确定要删除这篇文章吗？",
      onOk: async () => {
        setConfirmLoading(true);
        try {
          await deleteArticle(id);
          message.success("删除成功");
          // 刷新文章列表
          const res = await getArticles(1, 10);
          setDataSource(res.data);
        } catch (error) {
          message.error("删除失败");
        }
        setConfirmLoading(false);
      },
    });
  };

  // 添加组件挂载时加载初始数据的useEffect
  useEffect(() => {
    const loadInitialData = async () => {
      try {
        const res:any = await getArticles(currentPage, pageSize);
        res.data.forEach((v: Article) => {
          v.content = v.content.slice(0, 150);
        });
        setDataSource(res.data);
        setTotal(res.total);
      } catch (error) {
        message.error("加载数据失败");
      }
    };
    loadInitialData();
  }, [currentPage, pageSize]); // 依赖页码和每页数量变化 // 依赖数组为空，仅在组件挂载时执行

  return (
    <div>
      <h2>文章列表</h2>
      <Button
        type="primary"
        style={{ marginBottom: 16 }}
        onClick={() => navigate("/blog/articles/add")}
      >
        新增文章
      </Button>
      <Input
        placeholder="搜索文章标题..."
        value={searchText}
        onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
          setSearchText(e.target.value)
        }
        onKeyPress={(e: React.KeyboardEvent<HTMLInputElement>) =>
          e.key === "Enter" && handleSearch()
        }
        style={{ marginBottom: 16, marginLeft: 16, width: 200 }}
      />
      <Button
        type="primary"
        onClick={() => handleSearch()}
        style={{ marginBottom: 16, marginLeft: 8 }}
      >
        搜索
      </Button>
      <Table
        dataSource={dataSource}
        columns={columns}
        rowKey="id"
        pagination={{
          current: currentPage,
          pageSize: pageSize,
          total: total,
          pageSizeOptions: ["10", "20", "30"],
          onChange: (page: number, size: number) => {
            setCurrentPage(page);
            setPageSize(size);
            handleSearch(page); // 触发搜索时使用新页码
          },
        }}
      />
    </div>
  );
};

export default BlogArticles;
